// Prevents additional console window on Windows in release, DO NOT REMOVE!!
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]

use std::sync::Arc;
use tokio::sync::Mutex;
use cool_red_ai_client_lib::xiaohongshu::XiaohongshuService;
use serde_json::Value;

// 全局服务实例
lazy_static::lazy_static! {
    static ref XIAOHONGSHU_SERVICE: Arc<Mutex<XiaohongshuService>> = {
        Arc::new(Mutex::new(XiaohongshuService::new().unwrap()))
    };
}

// 启动Node.js浏览器服务器
async fn start_browser_server() -> Result<(), String> {
    println!("启动Node.js浏览器服务器...");
    
    let script_path = std::env::current_dir()
        .map_err(|e| format!("获取当前目录失败: {}", e))?
        .join("scripts")
        .join("browser-server.js");
    
    if !script_path.exists() {
        return Err(format!("浏览器服务器脚本不存在: {}", script_path.display()));
    }
    
    // 检查服务器是否已经在运行
    let client = reqwest::Client::new();
    match client.get("http://localhost:3001/health")
        .timeout(std::time::Duration::from_secs(2))
        .send()
        .await
    {
        Ok(_) => {
            println!("浏览器服务器已在运行");
            return Ok(());
        }
        Err(_) => {
            println!("浏览器服务器未运行，正在启动...");
        }
    }
    
    // 启动Node.js服务器
    let mut command = tokio::process::Command::new("node");
    command.arg(script_path);
    
    match command.spawn() {
        Ok(_) => {
            // 等待服务器启动
            tokio::time::sleep(tokio::time::Duration::from_secs(3)).await;
            
            // 验证服务器是否启动成功
            match client.get("http://localhost:3001/health")
                .timeout(std::time::Duration::from_secs(5))
                .send()
                .await
            {
                Ok(response) => {
                    if response.status().is_success() {
                        println!("浏览器服务器启动成功");
                        Ok(())
                    } else {
                        Err(format!("服务器响应异常: {}", response.status()))
                    }
                }
                Err(e) => {
                    Err(format!("无法连接到浏览器服务器: {}", e))
                }
            }
        }
        Err(e) => {
            Err(format!("启动浏览器服务器失败: {}", e))
        }
    }
}

#[tauri::command]
async fn xiaohongshu_open_login_page() -> Result<serde_json::Value, String> {
    let service = XIAOHONGSHU_SERVICE.lock().await;
    match service.open_login_page().await {
        Ok(_) => Ok(serde_json::json!({
            "success": true,
            "message": "登录页面已打开，请在浏览器中完成登录"
        })),
        Err(e) => Ok(serde_json::json!({
            "success": false,
            "message": format!("打开登录页面失败: {}", e)
        }))
    }
}

#[tauri::command]
async fn xiaohongshu_check_status() -> Result<serde_json::Value, String> {
    let service = XIAOHONGSHU_SERVICE.lock().await;
    match service.check_status().await {
        Ok(is_logged_in) => Ok(serde_json::json!({
            "isLoggedIn": is_logged_in,
            "message": if is_logged_in { "已登录" } else { "未登录" }
        })),
        Err(e) => Ok(serde_json::json!({
            "isLoggedIn": false,
            "message": format!("检查登录状态失败: {}", e)
        }))
    }
}

#[tauri::command]
async fn xiaohongshu_get_login_info_and_save() -> Result<serde_json::Value, String> {
    let service = XIAOHONGSHU_SERVICE.lock().await;
    match service.get_login_info_and_save().await {
        Ok(result) => {
            if result.success {
                Ok(serde_json::json!({
                    "success": true,
                    "message": result.message,
                    "account": result.account,
                    "cookies": result.cookies,
                    "token": result.token
                }))
            } else {
                Ok(serde_json::json!({
                    "success": false,
                    "message": result.message
                }))
            }
        },
        Err(e) => Ok(serde_json::json!({
            "success": false,
            "message": format!("获取登录信息失败: {}", e)
        }))
    }
}

#[tauri::command]
async fn xiaohongshu_sync_data(account_id: String) -> Result<serde_json::Value, String> {
    let service = XIAOHONGSHU_SERVICE.lock().await;
    match service.sync_data(&account_id).await {
        Ok(result) => {
            if result.success {
                Ok(serde_json::json!({
                    "success": true,
                    "message": result.message,
                    "data": result.data
                }))
            } else {
                Ok(serde_json::json!({
                    "success": false,
                    "message": result.message
                }))
            }
        },
        Err(e) => Ok(serde_json::json!({
            "success": false,
            "message": format!("同步失败: {}", e)
        }))
    }
}

#[tauri::command]
async fn xiaohongshu_switch_account(account_id: String) -> Result<serde_json::Value, String> {
    let service = XIAOHONGSHU_SERVICE.lock().await;
    match service.switch_account(&account_id).await {
        Ok(_) => Ok(serde_json::json!({
            "success": true,
            "message": "切换账号成功"
        })),
        Err(e) => Ok(serde_json::json!({
            "success": false,
            "message": format!("切换账号失败: {}", e)
        }))
    }
}

#[tauri::command]
async fn xiaohongshu_get_current_account() -> Result<serde_json::Value, String> {
    let service = XIAOHONGSHU_SERVICE.lock().await;
    match service.get_current_account().await {
        Ok(account) => {
            if let Some(acc) = account {
                Ok(serde_json::json!(acc))
            } else {
                Ok(serde_json::json!(null))
            }
        },
        Err(e) => Ok(serde_json::json!({
            "error": format!("获取当前账号失败: {}", e)
        }))
    }
}

#[tauri::command]
async fn xiaohongshu_publish(title: String, content: String, images: Option<Vec<String>>) -> Result<serde_json::Value, String> {
    let service = XIAOHONGSHU_SERVICE.lock().await;
    match service.publish(&title, &content, images).await {
        Ok(_) => Ok(serde_json::json!({
            "success": true,
            "message": "发布成功"
        })),
        Err(e) => Ok(serde_json::json!({
            "success": false,
            "message": format!("发布失败: {}", e)
        }))
    }
}

fn main() {
    tauri::Builder::default()
        .plugin(tauri_plugin_opener::init())
        .plugin(tauri_plugin_dialog::init())
        .setup(|_app| {
            // 在应用启动时启动浏览器服务器
            tauri::async_runtime::spawn(async {
                if let Err(e) = start_browser_server().await {
                    eprintln!("启动浏览器服务器失败: {}", e);
                }
            });
            Ok(())
        })
        .invoke_handler(tauri::generate_handler![
            xiaohongshu_open_login_page,
            xiaohongshu_check_status,
            xiaohongshu_get_login_info_and_save,
            xiaohongshu_sync_data,
            xiaohongshu_switch_account,
            xiaohongshu_get_current_account,
            xiaohongshu_publish
        ])
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}
